package utils.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class FileUtil {

    /**
     * writeFile(targetFile, source, "UTF-8");
     * @param file
     * @param content
     * @param fileEncoding
     * @throws IOException
     */
    public static void writeFile(File file, String content, String fileEncoding) throws IOException {
        FileOutputStream fos = new FileOutputStream(file, false);
        OutputStreamWriter osw;
        if (fileEncoding == null) {
            osw = new OutputStreamWriter(fos);
        } else {
            osw = new OutputStreamWriter(fos, fileEncoding);
        }

        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(content);
        bw.close();
    }

    /**
     * writeFile(targetFile, "UTF-8");
     */
    public static String readFile(File file, String fileEncoding) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr;
        if (fileEncoding == null) {
            isr = new InputStreamReader(fis);
        } else {
            isr = new InputStreamReader(fis, fileEncoding);
        }

        BufferedReader br = new BufferedReader(isr);
        StringBuilder context = new StringBuilder();

        String line = br.readLine();
        while(line != null) {
            context.append(line).append("\n");
            line = br.readLine();
        }
        return context.toString();
    }
}
